<style src="@/css/components/form.css"></style>
<style src="@/css/components/button.css"></style>
<style>
.create-training {
    padding:60px 0;
    background-color: #fff;
}

.training-editor {
    width:100%;
    max-width:800px;
}

.training-text {
    width:400px;
    height:90px;
}

.training-text textarea {
    width:400px;
    height: 80px;
    padding:10px;
    box-sizing:border-box;
    border:1px solid rgba(225,231,235,1);
    border-radius: 2px;
}

.clip-img {
    height: 300px;
    width: 400px;
}

.selectUser {
    width:400px;
    font-size:14px;
    font-family:PingFangSC-Regular;
    color:rgba(0,0,0,1);
    line-height:20px;
    color:#3A3A63;
}

.selectUser .viewUser {
    font-size:14px;
    color:#3577FB;
    margin-top:6px;
    display: inline-block;
    cursor: pointer;
}


.getQuest .el-dialog__header span{
    font-size:14px;
    color:#7485B1;
    margin-left:8px;
}

.quest-list-info {
    /*width:400px;*/
    padding-top:6px;
}

.quest-list-info ul li{
    display: flex;
    height:40px;
    justify-content: flex-start;
    align-items: center;
    font-size:14px;
    color:#7485B1;
    box-sizing: border-box;
}


.quest-list-info ul li .quest-list-fl i.iconfont {
    font-size:12px;
}

.quest-list-info ul li i.iconfont.check {
    color:#64C42D;
    font-size:12px;
}

.quest-list-info ul li i.delete {
    color:#7485B1;
    font-size:10px;
    cursor: pointer;
    display: none;
}

.quest-list-info ul li .question-list-cont:hover {
    /*width:400px;*/
    height:40px;
    background:rgba(245,247,250,1);
    border-radius:2px;
}

.quest-list-info ul li .question-list-cont:hover  i.iconfont.check {
    display: none;
}

.quest-list-info ul li .question-list-cont:hover  i.delete {
    display: block;
}

.quest-list-info ul li .el-form-item__label, .quest-list-info ul li .el-form-item__content {
    height: 32px;
    line-height: 32px;
    width:256px;
}

.quest-list-info ul li .el-input,.quest-list-info ul li .el-form-item .el-form-item__content .el-input__inner {
    height: 32px;
    line-height: 32px;
    padding: 0 10px;
}

.quest-list-info ul li .el-form-item__content .el-date-editor--daterange {
    width:100%;
    color:#C1C6D4;
}

.quest-list-info ul li .el-form-item__content .el-date-editor .el-range-input {
    font-size:12px;
}

.quest-list-info ul li .el-form-item .el-form-item__label {
    padding-right:20px;
}

.question-list-cont {
    width:400px;
    height: 40px;
    display: flex;
    padding:0 10px;
    box-sizing: border-box;
    align-items: center;
    justify-content: space-between;
}


.create-training .el-form .el-form-item  .el-form-item__content .el-date-editor--time-select {
    width:100%;
}
</style>

<template>
<div class="create-training">
    <el-form ref="form" :rules="rules" :model="form" label-width="130px">
        <el-form-item label="培训名称" prop="trainName">
            <el-input v-model="form.trainName" placeholder="请输入培训名称"></el-input>
        </el-form-item>

        <el-form-item label="培训人" prop="lecturer">
            <el-input v-model="form.lecturer" placeholder="请输入讲师名字"></el-input>
        </el-form-item>

        <el-form-item label="培训日期" prop="trainDate" required>
            <el-date-picker
                v-model="form.trainDate"
                type="date"
                value-format="yyyy-MM-dd"
                :picker-options="setStateTime"
                placeholder="请选择培训日期">
            </el-date-picker>
        </el-form-item>

        <el-form-item style="width:530px" label="培训时间" required>
            <el-col :span="11">
                <el-form-item prop="trainTime">
                    <el-time-select
                        placeholder="起始时间"
                        v-model="form.trainTime"

                        :picker-options="{
                          start: '06:00',
                          step: '00:15',
                          end: '22:00'
                        }">
                    </el-time-select>
                </el-form-item>
            </el-col>
            <el-col class="line" :span="2" style="text-align:center">-</el-col>
            <el-col :span="11">
                <el-form-item prop="trainExpiredTime">
                    <el-time-select
                        placeholder="结束时间"
                        v-model="form.trainExpiredTime"
                        :picker-options="{
                          start: '06:00',
                          step: '00:15',
                          end: '22:00',
                          minTime: form.trainTime
                        }">
                    </el-time-select>
                </el-form-item>
            </el-col>
        </el-form-item>

        <el-form-item label="培训地点" prop="address">
            <el-input v-model="form.address" placeholder="请输入培训地点" maxlength="20"></el-input>
        </el-form-item>


        <el-form-item label="培训人员" prop="enrollTargetMembers">
            <div class="selectFrom" @click="state = true" v-if="selectUserName.length <= 0"><i class="icon iconfont"></i> 选择人员</div>
            <div class="selectUser" v-if="selectUserName.length > 0">
                <div>{{ selectUserName.join('、')}}</div>
                <span class="viewUser" @click="state = true">更改</span>
            </div>
            <el-input v-model="form.enrollTargetMembers"  style="display:none"></el-input>
        </el-form-item>

        <el-form-item label="添加考试" >
            <div class="selectFrom" @click="setTestPaperListParam" ><i class="icon iconfont"></i> 选择考试</div>
            <div class="quest-list-info" v-if="testPaperListInfo.length > 0">
                <ul>
                    <li v-for="(item, index) in testPaperListInfo" :key="index">
                        <div class="question-list-cont">
                            <div class="quest-list-fl">
                                <i class="icon iconfont"></i>
                                {{item.ExamTitle}}
                            </div>
                            <i class="icon iconfont check"></i>
                            <i class="el-icon-close delete" @click="deleteTestPaper(index)"></i>
                        </div>
                        <el-form-item
                            label="考试时间"
                            required
                            :rules="{
                              required: true, message: '时间不能为空', trigger: 'blur'
                            }"

                        >
                            <el-date-picker
                                v-model="testPaperStorageTime[index]"
                                :picker-options="setStateTime"
                                type="daterange"
                                value-format="yyyy-MM-dd"
                                format="yyyy-MM-dd"
                                range-separator="~"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期">
                            </el-date-picker>
                        </el-form-item>
                    </li>
                </ul>
            </div>
        </el-form-item>

        <el-form-item label="添加问卷" >
            <div class="selectFrom" @click="setQuestionListParam"><i class="icon iconfont"></i> 选择问卷</div>
            <div class="quest-list-info" v-if="questionListInfo.length > 0">
                <ul>
                    <li v-for="(item, index) in questionListInfo" :key="index">
                        <div class="question-list-cont">
                            <div class="quest-list-fl">
                                <i class="icon iconfont"></i>
                                {{item.ExamTitle}}
                            </div>
                            <i class="icon iconfont check"></i>
                            <i class="el-icon-close delete" @click="deleteQuestion(index)"></i>
                        </div>
                        <el-form-item
                            label="问卷时间"
                            required
                            :rules="{
                              required: true, message: '时间不能为空', trigger: 'blur'
                            }"
                        >
                            <el-date-picker
                                v-model="questionStorageTime[index]"
                                :picker-options="setStateTime"
                                type="daterange"
                                format="yyyy-MM-dd"
                                value-format="yyyy-MM-dd"
                                range-separator="~"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期">
                            </el-date-picker>
                        </el-form-item>
                    </li>
                </ul>


            </div>
        </el-form-item>

        <el-form-item label="培训简介" prop="intro">
            <div class="training-editor">
                <editor :content="inputContent" v-model="form.intro" maxlength="5000" @input="getEdit"></editor>
            </div>
        </el-form-item>

        <el-form-item label="备注" >
            <div class="training-text">
                <textarea v-model="form.comment"></textarea>
            </div>
        </el-form-item>

        <el-form-item>
            <el-button type="primary" class="showdow" @click="createTrain('form')">保存培训</el-button>
        </el-form-item>
    </el-form>

    <selectUser :personnelState="state" @setUser="getUser" :recordSelectId="selectUserList"></selectUser>

    <selectTable
        :name="name"
        :type="type"
        @setTotalSelect="getTotalSelect"
        :dialogFormVisible="tabState"
        @setSelectTable="getSelectTable"
        @setPage="getPage"
        @setSelect="getSelect"
        @setSearch="getSearch"
        :selectList="paperType"
        :selectDefault="paperDefalutValue"
        :list="list"
        :listDefault="listDefault"
        :page="page"
        :pageSize="pageSize"
        :title="title"
        selectClass="getQuest"
        :total="total"
        :recordListIdS="recordListId"
    >

    </selectTable>

</div>
</template>

<script>
    import qs from 'qs'
    import editor from 'components/wangeditor.vue'
    import selectUser from "components/selectUser.vue"
    import selectTable from "components/selectTable.vue"

    export default {

        data() {
            var validateEditor = (rule, value, callback) => {
                if (value.trim() == '' || value.trim() == '<p><br></p>') {
                    callback(new Error('请输入培训简介'));
                }

                callback();
            }

            return {
                title:'',
                selectUserList:[], //总选中员工列表
                selectUserName:[], //总选中员工名称
                state:false, //培训人员弹窗状态
                tabState:false,  //问试卷弹窗状态
                page:1,
                pageSize:20,
                total:0,
                name:"", //记录返回的id名
                search:'', //获取查询内容
                list:[], //问试卷弹窗数据
                listDefault:[],
                paperType:[], // 试卷分类
                paperDefalutValue:{}, // 设置下拉分类key, value
                questionArrayId:[], //弹窗选择的问卷id
                testPaperArrayId:[], //弹窗选择的试卷id
                questionListInfo:[], //问卷列表信息
                questionStorageTime:[], //问卷临时存储时间
                testPaperListInfo:[], //试卷列表信息
                testPaperStorageTime:[],//试卷临时存储时间
                recordListId:[], //回传的id （试问卷再次打开记录的值）
                path:[
                    {
                        name:'培训学习',
                        path:'/study/plan-list'
                    },
                    {
                        name:'培训管理',
                        path:'/training/training-manage'
                    },
                    {
                        name:'编辑培训'
                    }
                ],

                form: {
                    TrainID:"" || this.$route.query.TrainID,
                    trainName: "",
                    lecturer : "",
                    address  : "",
                    trainDate: "",
                    comment  : "",
                    intro    : "",
                    enrollTargetMembers:"",
                    trainTime: "",
                    trainExpiredTime: "",
                    examCollection: [],
                    QNRCollection: []
                },

                rules: {
                    trainName: [
                        { required: true, message: '请输入培训名称', trigger: 'blur' },
                    ],

                    lecturer: [
                        { required: true, message: '请输入培训人', trigger: 'blur' },
                    ],

                    enrollTargetMembers: [
                        { required: true, message: '请选择培训人员', trigger: 'change' },
                    ],

                    intro:[
                        { required: true, validator: validateEditor, trigger: 'blur' },
                        {  max: 5000, message: '最大可输入为5000字', trigger: 'blur' }
                    ],

                    trainTime:[
                        { required: true, message: '请选择时间', trigger: 'blur' }
                    ],

                    trainExpiredTime:[
                        { required: true, message: '请选择时间', trigger: 'blur' }
                    ],

                    trainDate:[
                        { required: true, message: '请选择培训时间', trigger: 'blur' }
                    ]
                },

                setStateTime:{
                    disabledDate(time) {
                        return time.getTime() < Date.now() - 1000 * 60 *60*24
                    }
                }
            }
        },

        components: {
            editor,
            selectUser,
            selectTable
        },

        methods:{


            // 提交组织信息
            createTrain(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        if(!this.verificationTestPaper()) {
                            this.$message.error('请选择试卷的时间')
                            return false;
                        }

                        if(!this.verificationQuestion()) {
                            this.$message.error('请选择问卷的时间')
                            return false;
                        }

                        Array.isArray(this.form.enrollTargetMembers) && ( this.form.enrollTargetMembers = this.form.enrollTargetMembers.join(','))
                        this.form.examCollection = JSON.stringify(this.mergeData(this.testPaperArrayId, this.testPaperStorageTime))
                        this.form.QNRCollection = JSON.stringify(this.mergeData(this.questionArrayId, this.questionStorageTime))
                        //提交请求
                        this.editTrain()
                    }
                })
            },

            // 提交组织信息请求
            editTrain() {
                axios.post('/com/train/edit', qs.stringify(this.form)).then((res) => {
                    var d = res.data
                    if(d.flag == 1){
                        this.$router.push({'path': '/training/training-manage'})
                    }else {
                        this.$message.error(d.msg)
                    }
                })
            },

            //试卷选择验证
            verificationTestPaper() {
                return this.testPaperArrayId.every((value,index)=>{
                    return Array.isArray(this.testPaperStorageTime[index]) && this.testPaperStorageTime[index].length == 2
                })
            },

            //试卷选择验证
            verificationQuestion() {
                return this.questionArrayId.every((value,index)=>{
                    return Array.isArray(this.questionStorageTime[index]) && this.questionStorageTime[index].length == 2
                })
            },


            // 合并提交数据
            mergeData(arrayId, time) {
                return arrayId.map((value, index)=>{
                    return {
                        "examLibID" : value,
                        "examStartTime": time[index][0],
                        "examStopTime": time[index][1],
                    }
                })
            },


            // 获取选中的员工
            getUser(arrId, value) {
                this.state = value

                if(!Array.isArray(arrId)) {
                    this.$message.error('糟糕,出错了')
                    return;
                }

                if(arrId.length <= 0) return;

                this.selectUserList = arrId
                this.form.enrollTargetMembers = this.selectUserList

                this.getUserName()
            },


            // 获取选中试(问)卷数据
            getSelectTable(state, param) {

                this.tabState = state


                if(!param) return ;

                if(Array.isArray(param.list) ) {
                    let type

                    if( param.name == 'testPaper' ) {
                        type = 1
                        this.testPaperArrayId = param.list
                    } else {
                        type = 2
                        this.questionArrayId = param.list
                    }


                    this.getLibListByExamIDs({
                        examIDs:param.list.join(','),
                        infoType: type
                    }).then((value)=>{
                        if(!value || !Array.isArray(value)) return;
                        param.name == 'testPaper' ? (this.testPaperListInfo = value) : ( this.questionListInfo = value )
                    })

                }
            },

            // 获取试卷（问)信息(根据id)
            getLibListByExamIDs(param) {
                return new Promise((resolve, reject)=>{
                    axios.post('/com/exam/getLibListByExamIDs', qs.stringify(param)).then((res) => {
                        var d = res.data
                        if(d.flag == 1){
                            resolve(d.data.Rows)
                        }else {
                            this.$message.error(d.msg)
                        }
                    })
                })
            },

            // 获取选中员工的名称
            getUserName() {

                if(this.selectUserList.length <= 0) return;

                axios.post('/com/employee/getEmployeesName', qs.stringify({'employeesIDs':this.selectUserList.join(',')})).then((res) => {
                    var d = res.data
                    if(d.flag == 1){
                        this.selectUserName = d.data.Rows
                    }else {
                        this.$message.error(d.msg)
                    }
                })
            },

            // 弹窗查询触发
            getSearch(value, type) {
                this.search = value
                type == 'testPaper' ?  this.getTestPaper() : this.getQNRLibList()
            },

            // 获取弹窗体系切换
            getSelect(value) {
                this.infoCateID = value
                this.getTestPaper()
            },

            // 获取弹窗分页切换
            getPage(value, type) {
                this.page = value
                type == 'testPaper' ?  this.getTestPaper() : this.getQNRLibList()
            },

            // 富文本编辑
            getEdit(value) {
                this.form.intro = value
            },

            // 获取当前选中数
            getTotalSelect(value, type) {

                type == 'testPaper' ?  (this.title = `选择试卷<span>已选择${value}张试卷</span>`) : (this.title = `选择问卷<span>已选择${value}张问卷</span>`)
            },

            // 获取问卷列表
            getQNRLibList() {
                this.pageSize = 4

                axios.post('/com/exam/getQNRLibList', qs.stringify({
                    // my:1,
                    keywords:this.search,
                    page:this.page,
                    pagesize:this.pageSize
                })).then((res) => {
                    var d = res.data
                    if(d.flag == 1){
                        this.tabState = true
                        this.list = d.data.Rows
                        this.total = d.data.Total
                    }else {
                        this.$message.error(d.msg)
                    }
                })
            },

            // 获取试卷列表
            getTestPaper() {
                this.pageSize = 4
                axios.post('/com/exam/getLibList', qs.stringify({
                    // my:1,
                    keywords:this.search,
                    page:this.page,
                    pagesize:this.pageSize,
                    infoCateID:this.infoCateID
                })).then((res) => {
                    var d = res.data
                    if(d.flag == 1){
                        this.tabState= true
                        this.list = d.data.Rows
                        this.total = d.data.Total
                    }else {
                        this.$message.error(d.msg)
                    }
                })
            },


            // 获取试卷体系
            getTestPaperInfoCateList() {
                axios.post('/com/exam/getQuestionInfoCateList').then((res) => {
                    var d = res.data
                    if(d.flag == 1){
                        //获取下拉数据
                        this.paperType = d.data
                        // 设置试卷下拉参数分类
                        this.paperDefalutValue =  { label:'CateName', value:'InfoCateID'}
                    }else {
                        this.$message.error(d.msg)
                    }
                })
            },


            // 唤起添加问卷
            setQuestionListParam() {
                // 获取问卷
                this.getQNRLibList()

                //设置表格参数
                this.listDefault = [
                    { key:"ExamLibID", name:"selection", width:'12.5%' },
                    { key:"ExamTitle", name:"问卷名称", width:'62.5%' },
                    { key:"CreateTime", name:"创建时间",width:'25%' }
                ]

                this.title = `选择问卷<span>已选择0张问卷</span>`
                this.page = 1
                this.name = "ExamLibID"
                this.type = "question"
                // 更新插件中的值


                this.recordListId = this.questionArrayId
            },

            // 删除选择的问卷
            deleteQuestion(index) {
                // 删除问卷列表
                this.questionListInfo.splice(index, 1)
                // 删除问卷临时存储的时间
                this.questionStorageTime.splice(index,1)
                // 删除问卷id
                this.questionArrayId.splice(index, 1)
            },

            // 唤起添加考试
            setTestPaperListParam() {
                // 获取体系并设置体系
                this.getTestPaperInfoCateList()

                // 获取试卷列表
                this.getTestPaper()

                //设置表格参数
                this.listDefault = [
                    { key:"ExamLibID", name:"selection", width:'16.6%' },
                    { key:"ExamTitle", name:"试卷名称", width:'50%' },
                    { key:"CreateTime", name:"创建时间",width:'33.3%' }
                ]

                this.title = `选择试卷<span>已选择0张试卷</span>`
                this.infoCateID = ""
                this.page = 1
                this.name = "ExamLibID"
                this.type = "testPaper"

                // 更新插件中的值
                this.recordListId = this.testPaperArrayId
                // this.testPaperArrayId = []
            },

            // 删除选择考试
            deleteTestPaper(index) {
                // 删除试卷列表
                this.testPaperListInfo.splice(index, 1)
                // 删除试卷临时存储的时间
                this.testPaperStorageTime.splice(index,1)
                // 删除问卷id
                this.testPaperArrayId.splice(index, 1)
            },

            // 获取培训详情
            getTrainInfo() {
                axios.post('/com/train/get', qs.stringify({TrainID:this.form.TrainID})).then((res) => {
                    var d = res.data
                    if(d.flag == 1){
                        let TrainID = this.form.TrainID
                        if(this.form.TrainID == d.data.TrainID) {
                            this.form = d.data
                        } else {
                            this.form = d.data
                            this.form.TrainID = TrainID
                        }


                        this.editParam()
                    }else {
                        this.$message.error(d.msg)
                    }
                })
            },

            editParam() {
                // 富文本回填
                this.inputContent = this.form.intro
                // 富文本培训人员
                this.selectUserList = this.form.enrollTargetMembers.map( v=> v.EmployeeID)
                this.selectUserName = this.form.enrollTargetMembers.map( v=> v.Username)
                this.form.enrollTargetMembers = this.selectUserList
                // // 试卷
                this.testPaperArrayId = this.form.examCollection.map( v => v.examLibID)
                this.testPaperListInfo = this.form.examCollection.map( (v) => {
                    return {
                        'examID': v.examID,
                        'examLibID':v.examLibID,
                        'examStartTime': v.examStartTime,
                        'examStopTime':v.examStopTime,
                        'ExamTitle': v.examTitle
                    }
                })
                // 试卷临时存储时间
                this.testPaperStorageTime = this.form.examCollection.map( v => [v.examStartTime , v.examStopTime])

                // 问卷
                this.questionArrayId = this.form.QNRCollection.map( v => v.examLibID)
                this.questionListInfo = this.form.QNRCollection.map( (v) => {
                    return {
                        'examID': v.examID,
                        'examLibID':v.examLibID,
                        'examStartTime': v.examStartTime,
                        'examStopTime':v.examStopTime,
                        'ExamTitle': v.examTitle
                    }
                })
                this.questionStorageTime = this.form.QNRCollection.map( v => [v.examStartTime , v.examStopTime])



            }
        },

        mounted() {
            // 设置面包屑
            this.$store.commit('setPath', this.path)

            this.form.TrainID = this.$route.query.TrainID

            this.getTrainInfo()

        }
    }
</script>
